import { defineStore } from 'pinia'
import axios from 'axios'
import api from '../api'

const API = import.meta.env.VITE_API_BASE || ''

export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    user: null,
    loading: false,
    error: ''
  }),
  getters: {
    isAuthenticated: (s) => !!s.token
  },
  actions: {
    setToken(t) {
      this.token = t
      localStorage.setItem('token', t)
      axios.defaults.headers.common['Authorization'] = `Bearer ${t}`
      try { api.defaults.headers.common['Authorization'] = `Bearer ${t}` } catch {}
    },
    clear() {
      this.token = ''
      this.user = null
      localStorage.removeItem('token')
      delete axios.defaults.headers.common['Authorization']
      try { delete api.defaults.headers.common['Authorization'] } catch {}
    },
    async login(email, password) {
      this.loading = true; this.error = ''
      try {
        const res = await api.post(`/api/auth/login`, { email, password })
        this.setToken(res.data.access_token)
        await this.fetchMe()
      } catch (e) {
        this.error = e?.response?.data?.detail || '登录失败'
        this.clear()
        throw e
      } finally { this.loading = false }
    },
    async register(name, email, password) {
      this.loading = true; this.error = ''
      try {
        await api.post(`/api/auth/register`, { name, email, password })
        await this.login(email, password)
      } finally { this.loading = false }
    },
    async fetchMe() {
      if (!this.token) return
      const res = await api.get(`/api/users/me`)
      this.user = res.data
    }
  }
})

// initialize default header
if (localStorage.getItem('token')) {
  axios.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem('token')}`
  try { api.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem('token')}` } catch {}
}
